﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Simple.Common.Application.Dtos;
using Simple.Common.Core.Hosting;

namespace Simple.Common.Application.BaseServices
{
    public class BaseAppService
    {
        private IMediator _bus;
        protected IMediator Bus
        {
            get { return _bus ??= ServiceProviderHelper.GetService<IMediator>(); }
        }

        private IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// Http context accessor
        /// </summary>
        public IHttpContextAccessor HttpContextAccessor
        {
            get => _httpContextAccessor;
            set => _httpContextAccessor ??= ServiceProviderHelper.GetService<IHttpContextAccessor>();
        }

        /// <summary>用例或查询处理结果</summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="data">返回数据</param>
        /// <param name="count"></param>
        /// <returns></returns>
        protected ResultDto<T> GetResultEntity<T>(T data, int count)
        {
            return GetResultEntity(data, "", 0, count);
        }
        /// <summary>用例或查询处理结果</summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="data">返回数据</param>
        /// <param name="msg">返回消息</param>
        /// <param name="errorCode">返回错误码</param>
        /// <param name="count">条数</param>
        /// <returns></returns>
        protected ResultDto<T> GetResultEntity<T>(T data, string msg = "", int errorCode = 0, int count = 0)
        {
            var resultDto = new ResultDto<T>();
            var flag = true;
            switch (data)
            {
                case int intData when intData < 0:
                case bool boolData when !boolData:
                case null:
                case string stringData when string.IsNullOrEmpty(stringData):
                    flag = false;
                    break;
            }

            if (!flag)
            {
                resultDto.Msg = msg;
                flag = errorCode == 200;
                resultDto.ErrorCode = errorCode;
            }
            resultDto.IsSuccess = flag;
            resultDto.Data = data;
            resultDto.Msg = msg;
            resultDto.Count = count;
            return resultDto;
        }
    }
}
